#include "BoundingBoxRenderer.h"
#include "MatrixHelper.h"
#include "GraphicsDeviceManager.h"

BoundingBoxRenderer::BoundingBoxRenderer()
{
}

BoundingBoxRenderer::~BoundingBoxRenderer()
{
}

void BoundingBoxRenderer::Initialize()
{
	Vertex vertices[8];

	vertices[0] = Vertex(Vector3f(-0.5f));
	vertices[1] = Vertex(Vector3f(-0.5f, -0.5f, 0.5f));
	vertices[2] = Vertex(Vector3f(-0.5f, 0.5f, -0.5f));
	vertices[3] = Vertex(Vector3f(-0.5f, 0.5f, 0.5f));
	vertices[4] = Vertex(Vector3f(0.5f, -0.5f, -0.5f));
	vertices[5] = Vertex(Vector3f(0.5f, -0.5f, 0.5f));
	vertices[6] = Vertex(Vector3f(0.5f, 0.5f, -0.5f));
	vertices[7] = Vertex(Vector3f(0.5f));

	m_pVertexBuffer = new VertexBuffer();
	m_pVertexBuffer->SetData(vertices, sizeof(Vertex) * 8);

	unsigned int indices[24] = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 2, 1, 3, 4, 6, 5, 7,  0, 4, 1, 5, 2, 6,  3, 7 };

	m_pIndexBuffer = new IndexBuffer();
	m_pIndexBuffer->SetData(indices, sizeof(unsigned int) * 24);

	m_bInitialized = true;
}

void BoundingBoxRenderer::Draw(const BoundingBox& boundingBox)
{
	if(!m_bInitialized)
	{
		Initialize();
	}

	Vector3f translation = (boundingBox.Max + boundingBox.Min) / 2.0f;
	Vector3f scale = boundingBox.Max - boundingBox.Min;

	// TODO: Disable lighting via LightManager
	glDisable(GL_LIGHTING);
	glDisable(GL_TEXTURE_2D);
	glPushMatrix();
	glTranslatef(translation.X, translation.Y, translation.Z);
	glScalef(scale.X, scale.Y, scale.Z);
	glBindBufferARB(GL_ARRAY_BUFFER_ARB, m_pVertexBuffer->GetID());
	glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, m_pIndexBuffer->GetID());
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_COLOR_ARRAY);
	glVertexPointer(3, GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(0));
	glColorPointer(4, GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(sizeof(Vector3f)));
	glDrawElements(GL_LINES, m_pIndexBuffer->GetElementCount(), GL_UNSIGNED_INT, 0);
	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_COLOR_ARRAY);
	glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
	glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
	glPopMatrix();
}

bool BoundingBoxRenderer::m_bInitialized = false;
IndexBuffer* BoundingBoxRenderer::m_pIndexBuffer = NULL;
VertexBuffer* BoundingBoxRenderer::m_pVertexBuffer = NULL;